﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text.RegularExpressions;
using NSoup.Nodes;
using NSoup;

namespace WAD.WEB.AppCode.Html
{
    public class HtmlFomat
    {
        public static string FomartToutiao(string html)
        {
            if (string.IsNullOrEmpty(html)) return html;
            html = Regex.Replace(html, "top.location.href = self.location.href", "");
            Document doc = NSoupClient.Parse(html);

            //只保留样式部分  去掉所以得js
            doc.Select("script").Remove();

            ////移除评论
            doc.Select(".comments-container").Remove();

            ////移除精彩推荐
            //doc.Select("#pageletRecommendation").Remove();

            ////移除精彩推荐
            //doc.Select("#pageletRelateNews").Remove();

            //doc.Select(".body-placeholder").Attr("style", "display:none");

            html = doc.Html();
            return html;
        }
        public static string FomartXwqq(string html)
        {
            if (string.IsNullOrEmpty(html)) return html;
            html = Regex.Replace(html, "top.location.href = self.location.href", "");
            html = Regex.Replace(html, "<script src=\"//mat1.gtimg.com/www/mobi/wx/js/hijackRel.min.js\"></script>", "");
            html = Regex.Replace(html, "display:none", "");
            MatchEvaluator eva = new MatchEvaluator(WordScrambler);
            html = Regex.Replace(html, "<img[^<>]*?\\ssrc=['\"]?(.*?)['\"].*?>", eva);
            return html;
        }

        public static string FormatWeiXin(string html)
        {
            if (string.IsNullOrEmpty(html)) return html;
            html = Regex.Replace(html, "data-src", "src");
            MatchEvaluator eva = new MatchEvaluator(WordScrambler);
            html = Regex.Replace(html, "<img[^<>]*?\\ssrc=['\"]?(.*?)['\"].*?>", eva);
            return html;
        }

        private static string WordScrambler(Match match)
        {
            var url = match.Groups[1].Value;
            var httpUrl = url;
            if (httpUrl.StartsWith("//"))
                httpUrl = "http:" + url;
            var img = match.Value;
            if (string.IsNullOrEmpty(url)) return img;
            var realUrl = ConfigurationManager.AppSettings["proxyimg"] + httpUrl;
            return img.Replace(url, realUrl);
        }
    }
}